<!-- 新增技术要求 -->
<template>
    <div id="dialog-container" class="dialog-container">
        <el-dialog v-dialogDrag title="新增实验技术要求" :fullscreen="isFullScreen" :custom-class="isFullScreen?'fullscreen-default-dialog':'vertical-center-dialog'" append-to-body :close-on-click-modal="false" :visible.sync="dialogVisible" @close="$emit('update:show', false)" :before-close="handleClose" :show="show" width="800px">
            <button type="button" aria-label="fullScreen" class="el-dialog__headerbtn" style="margin-right:25px;top:" @click="isFullScreen = !isFullScreen">
                <i class="el-dialog__close iconfont icon-fuzhicopy22"></i>
            </button>
            <el-form :model="formData" :rules="rules" :inline="true" ref="form" label-width="130px" size="small">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="零件号：" prop="partNumber">
                            <el-input v-model="formData.partNumber"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="零件图号：" prop="partGraphNumber">
                            <el-input v-model="formData.partGraphNumber"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="零件名称：" prop="partName">
                            <el-input v-model="formData.partName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材料牌号：" prop="materialNo">
                            <el-autocomplete v-model="formData.materialNo" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="零件类别：">
                            <el-select v-model="formData.partType.id" @change='changePartType' filterable placeholder="请选择" style="width: 200px;">
                                <el-option v-for="item in partTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="难度系数值：" prop="hardRate">
                            <el-input v-model="formData.hardRate" disabled></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="装炉数量：" prop="totalPartNo">
                            <el-input v-model="formData.totalPartNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图纸版本：">
                            <el-input v-model="formData.graphVersion"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目号：">
                            <el-input v-model="formData.projectNo"></el-input>
                        </el-form-item>
                    </el-col>
                    
                    <!-- <el-col :span="12">
            <el-form-item label="样品阶段：">
              <el-select v-model="formData.sampleStatusPhase" filterable placeholder="请选择" style="width: 200px;">
                <el-option v-for="item in phaseList" :key="item.code" :label="item.name" :value="item.code"></el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报验批次：">
              <el-input v-model="formData.batchNumber"></el-input>
            </el-form-item>
          </el-col>-->
        </el-row>
      </el-form>
      <br>
      <el-row>
        <edit-test-items-button @testData="getTestData" style="display: inline-block;"></edit-test-items-button>
         <el-button size="small" type="primary" @click="deleteBatch">批量删除</el-button>
      </el-row>
      <el-table ref="multipleTable" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
        <el-table-column prop="testType" label="检测类型" min-width="100">
          <template slot-scope="scope">
        <span >{{scope.row.testTypeStr}}</span>
</template>
        </el-table-column>
        <el-table-column prop="fieldName" label="检测项目" min-width="100">
<template slot-scope="scope">
  <span>{{scope.row.fieldName}}</span>
</template>
        </el-table-column>
        <el-table-column prop="position" label="检测位置" min-width="100">
    <template slot-scope="scope">
   <el-select v-if="rowObject == scope.row"  v-model="scope.row.position" filterable placeholder="请选择" @change='getPositionStr(scope.row)' style="width: 200px;">
                <el-option v-for="item in positionList" :key="item.id" :label="item.name" :value="item.code"></el-option>
              </el-select>
                <span v-else>{{scope.row.positionStr}}</span>
  </template>
        </el-table-column>
        <el-table-column prop="standard" label="标尺" min-width="80">
<template slot-scope="scope">
  <span>{{scope.row.standard}}</span>
</template>
       </el-table-column>

     </el-table-column> -->

                <el-table-column prop="operator" label="条件" min-width="80">
                    <template slot-scope="scope">
                       <el-select v-model="scope.row.operator" size="small" v-if="rowObject == scope.row" placeholder="请选择"  @change='getOperatorStr(scope.row)' style="width: 100px;" >
                  <el-option v-for="item in conditionList" :key="item.id" :label="item.name" :value="item.code"></el-option>
                </el-select>
                <span v-else>{{scope.row.operatorStr}}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="col1" label="值1 " min-width="80">
                    <template slot-scope="scope">
                        <el-input size="small" v-if="rowObject == scope.row" v-model="scope.row.col1" @change='changeCol1(scope.row)' :disabled='getStatus(scope.row,1)' placeholder="请输入下限">
                        </el-input>
                        <span v-else style="background:#f1f1f1;">{{scope.row.col1}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="fieldStandard.col1" label="下限（标准） " min-width="120">

                </el-table-column>
                <!-- <el-table-column prop="fieldStandard.col2" label="上限（标准） " min-width="120">
                </el-table-column> -->
                <el-table-column prop="col2" label="值2" min-width="80">
                    <template slot-scope="scope">
                        <el-input size="small" v-if="rowObject == scope.row" v-model="scope.row.col2" @change='changeCol2(scope.row)' :disabled='getStatus(scope.row,2)' placeholder="请输入上限">
                        </el-input>
                        <span v-else style="background:#f1f1f1;">{{scope.row.col2}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" min-width="100">
                     <!-- <template slot-scope="scope">
                        <el-input v-if="rowObject == scope.row" size="small" v-model="scope.row.unit" placeholder="请输入单位">
                        </el-input>
                        <span v-if="rowObject != scope.row">{{scope.row.unit}}</span>
                    </template>-->
                </el-table-column>
                <el-table-column prop="decimalPoint" label="小数点" min-width="100">
                   <!-- <template slot-scope="scope">
                        <el-input v-if="rowObject == scope.row" size="small" @change="addPoint(scope.row)" v-model="scope.row.decimalPoint" placeholder="请输入小数点">
                        </el-input>
                        <span v-if="rowObject != scope.row">{{scope.row.decimalPoint}}</span>
                    </template>-->
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="100">
                    <template slot-scope="scope">
                        <el-input v-if="rowObject == scope.row" size="small" v-model="scope.row.remark" placeholder="请输入内容">
                        </el-input>
                        <span v-if="rowObject != scope.row">{{scope.row.remark}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="" align="center" label="操作" min-width="160">
                    <template slot-scope="scope">
                        <el-button v-if="rowObject != scope.row" size="small" @click="handleEdit(scope.row)" type="primary" plain>
                            编辑</el-button>
                        <el-button v-if="rowObject == scope.row" size="small" @click="editData(scope.row)" type="primary" plain>保存</el-button>
                        <el-button v-if="rowObject == scope.row" size="small" @click="cancel(scope.row, scope.$index)">取消</el-button>
                        <el-popover placement="top" title="确认删除吗？" width="160" trigger="click" v-model="scope.row.visible">
                            <div style="text-align: right; margin: 0">
                                <el-button size="mini" type="text" @click="scope.row.visible=false">取消</el-button>
                                <el-button type="primary" size="mini" @click="deleteData(scope.row.id, scope.$index)">确定</el-button>
                            </div>
                            <el-button v-show="rowObject != scope.row" size="small" type="danger" slot="reference" plain>删除</el-button>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveData('form')">确 定</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import TestItemsButton from "./edit-test-items-button";
    import {
        postSavePart,
        getPartTypeList,
        getTypeList,
        getPositionList,
        getStandardCondition,
        getSampleStatusPhase,
        partFieldDelete,
        getMaterialNo
    } from "service/task";
    import {
        getLableFromList
    } from "utils/common";
    import {
        getPartInfo
    } from "../../../../service/task";
    export default {
        components: {
            "edit-test-items-button": TestItemsButton
        },
        data() {
            return {
                dialogVisible: false,
                formData: {
                    partType: {}
                },
                isFullScreen: false,
                tableData: [],
                editId: "",
                selectCount: 0,
                phaseList: [],
                partTypeList: [],
                typeList: [],
                positionList: [],
                conditionList: [],
                rowObject: {},
                materialNoList: [],
                oldRowObject: {},
                rules: {
                    partNumber: [{
                        required: true,
                        message: '请输入零件编号',
                        trigger: 'blur'
                    }],
                    partName: [{
                        required: true,
                        message: '请输入零件名称',
                        trigger: 'blur'
                    }],
                    hardRate: [{
                        required: true,
                        message: '请输入材料难度系数',
                        trigger: 'blur'
                    }],
                    materialNo: [{
                        required: true,
                        message: '请输入材料牌号',
                        trigger: 'blur'
                    }],
                    position: [{
                        required: true,
                        message: '请输入检测位置',
                        trigger: 'blur'
                    }],
                    partGraphNumber: [{
                        required: true,
                        message: '请输入零件图号',
                        trigger: 'blur'
                    }],
                    totalPartNo: [{
                        required: true,
                        message: '请输入装炉数量',
                        trigger: 'blur'
                    }]

                },
            };
        },
        props: {
            show: {
                type: Boolean,
                default: false
            },
            modifyId: {
                type: String
            }
        },
        watch: {
            show() {
                this.dialogVisible = this.show;
                this.tableData = [];
                this.formData = {
                    partType: {},
                    hardRate: 1,
                    materialNo: localStorage.getItem('materialNo') ? localStorage.getItem('materialNo') : ''
                };
                if (this.dialogVisible) {
                    getPositionList().then(res => {
                        this.positionList = res.data.result;
                    });
                    if (this.modifyId) {
                        this.loadPartData();

                    }
                }

            }
        },
        mounted() {
            this.materialNoList = [];
            getMaterialNo().then(res => {
                if (res.status == '200') {
                    let list = res.data;
                    for (let i = 0; i < list.length; i++) {
                        let object = {};
                        object['value'] = list[i];
                        this.materialNoList.push(object);
                    }
                }
            });
            // this.materialNoList = this.loadAll();
            getPartTypeList().then(res => {
                this.partTypeList = res.data.result;
            });
            getSampleStatusPhase().then(res => {
                this.phaseList = res.data.result;
            });
            getTypeList().then(res => {
                this.typeList = res.data.result;
            });
            getPositionList().then(res => {
                this.positionList = res.data.result;
            });
            getStandardCondition().then(res => {
                this.conditionList = res.data.result;
            });
        },
        methods: {
            getStatus(row, seq) {
                if (row.operator == 'range') {
                    return false;
                } else if (row.operator == 'choose'||row.operator=='equal') {
                    return true;
                } else {
                    if (seq == 1) {
                        return false;
                    } else {
                        return true;
                    }
                }
            },
            loadAll() {
                return [{
                        "value": "1",
                        "address": "长宁区新渔路144号"
                    },
                    {
                        "value": "2",
                        "address": "上海市长宁区淞虹路661号"
                    },
                    {
                        "value": "5",
                        "address": "上海市普陀区真北路988号创邑金沙谷6号楼113"
                    }
                ];
            },
            querySearchAsync(queryString, cb) {
                let materialNoList = this.materialNoList;
                let results = queryString ? materialNoList.filter(this.createStateFilter(queryString)) : materialNoList;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000);
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            handleSelect(item) {
                console.log(item);
            },
            // 获取表格多选的值
            handleSelectionChange(val) {
                this.selectList = val;
                this.selectCount = val.length;
            },
            deleteBatch() {
                if (this.selectCount <= 0) {
                    alert("您还未选择要删除的数据");
                    return;
                }

                let that = this;

                let confirm = this.$confirm('您确定删除选中的' + this.selectCount + '条记录吗?', '提示', {
                    // confirmButtonText: '确定',
                    // cancelButtonText: '取消',
                    type: 'warning'
                }).then(res => {
                    let ids = "";
                    this.selectList.forEach(function(e, index) {
                        if (e.id) {
                            ids += e.id + ",";
                        }
                    });
                    for(let i = 0; i < this.tableData.length; i++) {
                        for(let j = 0; j < this.selectList.length; j++) {
                            if(this.tableData[i] == this.selectList[j] ) {
                                this.tableData.splice(i, 1);  
                            }
                        }
                    }
                    if (ids == "") {
                        // this.loadPartData();
                        return;
                    }
                    ids = ids.substring(0, ids.length - 1);
                    partFieldDelete({
                        ids: ids.split(",")
                    }).then(res => {
                        if (res.data.success) {
                            this.$message({
                                message: res.data.message,
                                type: 'success',
                                duration: 1000
                            });
                            // this.loadPartData();
                        }
                    });
                }).catch(res => {
                    return
                });
            },

           // 值1，值2添加小数点
            addPoint(row) {
            let decimalPoint = row.decimalPoint;
            if(row.col1) {
                row.col1 = Number(row.col1).toFixed(decimalPoint);
             }
            if(row.col2) {
                row.col2 = Number(row.col2).toFixed(decimalPoint);
             }
            },

            // 新增
            changeCol1(row) {
                if (row.operator == 'range') {
                    if (row.orginalCol1) {
                        if (Number(row.col1) < Number(row.orginalCol1) ) {
                            this.$alert('下限应该检测标准范围内', "提示", {
                                type: "error"
                            });
                            return false;
                        }
                        if(row.orginalCol2 && Number(row.col1) > Number(row.orginalCol2)){
                            this.$alert('下限应该检测标准范围内', "提示", {
                                type: "error"
                            });
                            return false;
                        }
                    }
                }else if(row.operator=='ge'||row.operator=='gr'){
                    if (row.orginalCol1) {
                        if (Number(row.col1) < Number(row.orginalCol1) ) {
                            this.$alert('下限应该检测标准范围内', "提示", {
                                type: "error"
                            });
                            return false;
                        }
                    }
                }else if(row.operator=='le'||row.operator=='less'){
                    if (row.orginalCol1) {
                        if (Number(row.col1) > Number(row.orginalCol1) ) {
                            this.$alert('值1应该检测标准范围内', "提示", {
                                type: "error"
                            });
                            return false;
                        }
                    }
                }
                let decimalPoint = row.decimalPoint;
                let col1 = row.col1;
                if(decimalPoint && col1 ) {
                    row.col1 = Number(row.col1).toFixed(decimalPoint);
                }
                return true;
            },
            changeCol2(row) {
                if (row.operator != 'choose') {
                    if(row.col2){
                        if (row.orginalCol1 || row.orginalCol2) {
                            if (Number(row.col2) < Number(row.orginalCol1) || Number(row.col2) > Number(row.orginalCol2)) {
                                this.$alert('值2应该检测标准范围内', "提示", {
                                    type: "error"
                                });
                                return false;
                            }
                        }
                    }
                }
                let decimalPoint = row.decimalPoint;
                let col2 = row.col2;
                if(decimalPoint && col2) {
                    row.col2 = Number(row.col2).toFixed(decimalPoint);
                }
                return true;
            },
            getLableFromList(list, code) {
                if (list) {
                    return getLableFromList(list, code);
                } else {
                    return "";
                }
            },
            loadPartData() {
                getPartInfo(this.modifyId).then(res => {
                    this.formData = res.data.result;
                    this.partType = this.formData.partType;
                    if(this.partType == null) {
                        this.formData.partType = {
                            id: ''
                        }
                    }
                    this.tableData = this.formData.partFieldList;
                    this.tableData.forEach(e => {
                        e.orginalCol1 = e.fieldStandard.col1;
                        e.orginalCol2 = e.fieldStandard.col2;
                        this.initRowData(e);
                    })
                });
            },
            changePartType() {
                let type = this.formData.partType;
                if (type) {
                    this.partTypeList.forEach(t => {
                        if (t.id == type.id) {
                            this.formData.hardRate = t.hardRate;
                            return;
                        }
                    });
                }
            },
            getTestData(fieldData) {
                console.log(fieldData);
                if (fieldData) {
                    fieldData.forEach(e => {
                        let partField = {};
                        partField.orginalCol1 = e.col1;
                        partField.orginalCol2 = e.col2;

                        partField.device = e.testField.device;
                        partField.fieldName = e.testField.fieldName;
                        partField.position = e.testField.testPart;
                        partField.testType = e.testField.testType;
                        partField.standard = e.standardName;
                        partField.operator = e.operator;
                        partField.standard = e.standardName;
                        partField.unit = e.unit;
                        partField.decimalPoint = e.decimalPoint;
                        partField.col1 = e.col1;
                        partField.col2 = e.col2;

                        partField.fieldStandard = e;

                        this.initRowData(partField);

                        this.tableData.push(partField);
                    });
                }
            },

            initRowData(e) {
                e.testTypeStr = getLableFromList(this.typeList, e.testType);
                e.positionStr = getLableFromList(this.positionList, e.position);
                e.operatorStr = getLableFromList(this.conditionList, e.operator);
            },

            getPositionStr(row) {
                row.positionStr = getLableFromList(this.positionList, row.position);
            },

            getOperatorStr(row) {
                row.operatorStr = getLableFromList(this.conditionList, row.operator);
            },

            handleClose() {
                /* 关闭的时候更新状态值 */
                this.dialogVisible = false;
            },
            // getTestData(val) {
            //   this.tableData.push(val);
            // },
            handleEdit(row) {
                this.editId = row.id;
                this.rowObject = row;
                this.oldRowObject.position = this.rowObject.position;
                this.oldRowObject.positionStr = this.rowObject.positionStr;
                this.oldRowObject.unit = this.rowObject.unit;
                this.oldRowObject.decimalPoint = this.rowObject.decimalPoint;
                this.oldRowObject.remark = this.rowObject.remark;
                this.oldRowObject.col1 = this.rowObject.col1;
                this.oldRowObject.col2 = this.rowObject.col2;
                this.oldRowObject.operator = this.rowObject.operator;
                 this.oldRowObject.operatorStr = this.rowObject.operatorStr;
            },
            cancel(row, index) {
                this.editId = '';
                row.position = this.oldRowObject.position;
                row.positionStr = this.oldRowObject.positionStr;
                row.unit = this.oldRowObject.unit;
                row.decimalPoint = this.oldRowObject.decimalPoint;
                row.remark = this.oldRowObject.remark;
                row.col1 = this.oldRowObject.col1;
                row.col2 = this.oldRowObject.col2;
                row.operator = this.oldRowObject.operator;
                row.operatorStr = this.oldRowObject.operatorStr;
                this.rowObject = {};
            },
            // 删除
            deleteData(id, index) {
                if (id) {
                    let jsonArray = [];
                    jsonArray[jsonArray.length] = id;
                    let jsonObject = {
                        "ids": jsonArray
                    };
                    partFieldDelete(jsonObject).then(res => {
                        if (res.data.success) {
                            this.$message({
                                message: res.data.message,
                                type: 'success',
                                duration: 1000
                            });
                        }
                        this.tableData.splice(index, 1);
                    });
                } else {
                    this.tableData.splice(index, 1);
                }
            },
            // 编辑
            editData(id) {
                this.editId = "";
                this.rowObject = {};
            },
            saveData(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.formData.partFieldList = this.tableData;
                        for (let i = 0; i < this.formData.partFieldList.length; i++) {
                            let result = this.changeCol1(this.formData.partFieldList[i]);
                            if (!result) {
                                return;
                            }
                            result = this.changeCol2(this.formData.partFieldList[i]);
                            if (!result) {
                                return;
                            }
                            if (this.formData.partFieldList[i].fieldStandard == this.formData.partFieldList[i]) {
                                this.formData.partFieldList[i].fieldStandard = {};
                            }
                        }
                        let params = this.formData;
                        let tableDataList = this.formData.partFieldList;
                        for(let i = 0; i < tableDataList.length; i++) {
                             let    a=i+1;
                            if(tableDataList[i].position==null ||tableDataList[i].position == "") {
                               alert("第"+a+"行,检测位置不能为空,请点击编辑修改");
                               return;
                            }
                             if(tableDataList[i].operator==null ||tableDataList[i].operator == "") {
                               alert("第"+a+"行,条件不能为空,请点击编辑修改");
                               return;
                            }
                           
                         let col1 = this.formData.partFieldList[i]['col1'];
                        let col2 = this.formData.partFieldList[i]['col2'];
                        let operator= this.formData.partFieldList[i]['operator'];
                         
                        if(operator=='range'){
                            if(col1==null || col1=="" || col2==null || col2==""){
                              
                                alert("第"+a+"行,值1，值2不能为空,请点击编辑修改");
                               return; 
                            }
                          if( !(Number.parseFloat(col2)>Number.parseFloat(col1))) {
                            this.$alert("第"+a+"行，值2应大于值1", "提示", {
                                type: "warning"
                            });
                            return;
                            }
                        }if(operator!='choose'){
                            if(col1==null || col1==""){
                                alert("第"+a+"行,值1不能为空,请点击编辑修改");
                               return; 
                            }
                        }

                        }
                        postSavePart(params).then(res => {
                            if (res.data.success) {
                                localStorage.setItem('materialNo', this.formData.materialNo);
                                this.$message({
                                    message: res.data.message,
                                    type: 'success',
                                    duration: 1000
                                });
                                this.$emit('refreshAdd');
                                this.dialogVisible = false;
                            } else {
                                this.$alert(res.data.message, "提示", {
                                    type: "error"
                                });
                            }
                        });
                    }
                })
            }
        }
    };

</script>
